#include "test.h"

int uart_open(int comport);
int uart_setting(int fd, int baud_rate, int data_bit, char parity_bit, int stop_bit);

int test_uart_select()
{
    int fd;
    char buff[BUFFER_SIZE];

    fd_set inset1;
    struct timeval tv;


    // 打开串口
    if((fd = uart_open(0)) < 0)
    {
        perror("open_port error");
        return -1;
    }

    // 配置串口
    if((uart_setting(fd, 115200, 8, 'N', 1)) < 0)
    { 
        perror("set_opt error");
        return -1;
    }

    // 初始化读集合inset1，并在集合中加入相应的描述集合
    FD_ZERO(&inset1);
    FD_SET(fd,&inset1);


    // 循环测试该文件描述符是否就绪，调用select函数对相关文件描述符做出操作
    while (1)
    {
        tv.tv_sec = 20;
        tv.tv_usec = 0;
        if (FD_ISSET(fd,&inset1))
        {
            if (select(fd+1, &inset1, (fd_set *)0, (fd_set *)0, &tv) < 0)
            {
                perror("select");
            }
            else
            {
                if ( (read(fd, buff, BUFFER_SIZE)) > 0 )
                {
                    if (strncmp(buff, "quit", 4) == 0)
                        break;
                    write(fd, buff, strlen(buff));
                }
            }
        }
    }
    close(fd);
    return 0;
}